<?php
class Router {
	const MODULE_VAR_NAME = 'm';
	const CONTROL_VAR_NAME = 'c';
	const ACTION_VAR_NAME = 'a';
	const DEFAULT_CONTROL = 'Index';
	const DEFAULT_ACTION = 'index';
	
	protected $regVars = array(
		'{page}'  => '(\d+)',
		'{id}'    => '(\d+)',
		'{year}'  => '(\d{4})',
		'{month}' => '(\d{1,2})',
		'{day}'   => '(\d{1,2})',
		'{alias}' => '(/^[a-z]+[a-z0-9\-_\.]+$/i)',
	);
	
	/**
	 * 路由配置信息
	 *
	 * @var array
	 */
	protected $config = array();
	
	/**
	 * 是否启用URL重写
	 *
	 * @var boolean
	 */
	private $isRewrite = false;
	
	/**
	 * 控制器名
	 *
	 * @var string
	 */
	private $controlName;
	
	/**
	 * 动作名
	 *
	 * @var string
	 */
	private $actionName;
	
	/**
	 * 查询参数
	 *
	 * @var array
	 */
	private $params = array();
	
	private function __construct() {}
	
	public static function getInstance() {
		static $instance = null;
		if (!($instance instanceof self)) {
			$instance = new self();
		}
		return $instance;
	}
	
	/**
	 * 设置路由配置信息
	 *
	 * @param array $config
	 */
	public function setRouteMap($config) {
		if (is_array($config)) {
			$this->config = array();
			foreach ($config as $re => $mc) {
				$re = str_replace(array_keys($this->regVars), array_values($this->regVars), $re);
				$this->addRule($re, $mc);	
			}
		}
	}
	
	/**
	 * 设置URL模式
	 */
	public function setUrlMode() {
		
	}
	
	/**
	 * 添加规则
	 *
	 * @param string $rule 规则
	 * @param string $map 路由信息
	 */
	public function addRule($rule, $map) {
		$this->config[$rule] = $map; 
	}
	
	public function getControl() {
		return $this->controlName;
	}
	
	public function getAction() {
		return $this->actionName;
	}
	
	public function getParams() {
		return $this->params;
	}

	/**
	 * 解析URL 
	 */
	public function dispath() {
		$query = $_SERVER['QUERY_STRING'];
		if ($this->isRewrite) {
			
		} else {
			parse_str($query, $this->params);
			$this->controlName = isset($this->params[self::CONTROL_VAR_NAME]) 
								? $this->params[self::CONTROL_VAR_NAME] 
								: self::DEFAULT_CONTROL;
			$this->actionName = isset($this->params[self::ACTION_VAR_NAME]) 
								? $this->params[self::ACTION_VAR_NAME] 
								: self::DEFAULT_ACTION;
			unset($this->params[self::CONTROL_VAR_NAME]);
			unset($this->params[self::ACTION_VAR_NAME]);
		}
	}
	
	/**
	 * 生成URL
	 *
	 */
	public function url($ca, $qs) {
		list($c, $a) = explode('.', $ca);
		if (is_array($qs)) {
			$qs = http_build_query($qs); 
		}
		return '?'.self::CONTROL_VAR_NAME.'='.$c.'&'.self::ACTION_VAR_NAME.'='.$a.($qs?'&'.$qs:'');
	}
}
?>